<template>
  <div class="JNPF-common-layout">
    <div class="JNPF-common-layout-center">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent label-width="80px">
          <el-col :span="6">
            <el-form-item  label="客户名称">
              <el-select v-model="listQuery.fsiteNo" 
              v-if="this.$store.state.user.fsiteLevel==3"
              disabled clearable filterable class="filter-item" placeholder="请选择客户名称">
                <el-option
                  v-for="item in fsiteNoBelongOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
              <el-select v-model="listQuery.fsiteNo" 
              v-else
              clearable filterable class="filter-item" placeholder="请选择客户名称" @change="getFpointOptions(listQuery.fsiteNo)">
          <el-option
            v-for="item in fsiteNoBelongOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属楼">
        <el-select v-model="listQuery.fpointNo" clearable filterable class="filter-item" placeholder="请选择所属楼">
          <el-option
            v-for="item in fpointOptions2"
            :key="item.fpointNo"
            :label="item.fpointName"
            :value="item.fpointNo"/>
        </el-select>
      </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="楼层名称">
        <el-input v-model="listQuery.flayerName" clearable class="filter-item" style="width: 200px;" placeholder="请输入楼层名称"/>
      </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
        <el-button type="primary" @click="handleFilter">查找</el-button>
        <el-button type="success" @click="handleCreate">添加</el-button>
      </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="JNPF-common-layout-main JNPF-flex-main">
       <!-- 查询结果 -->
    <JNPF-table v-loading="listLoading" :data="list">
      <el-table-column :width="buttonColor.operationTwo" align="center" label="操作" class-name="small-padding">
        <template slot-scope="scope">
          <el-button type="text" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column :index="indexMethod" :width="buttonColor.line" align="center" label="序" type="index" />
      <el-table-column :formatter="formatSite" align="left" label="客户名称" prop="fsiteNo" />
      <el-table-column :formatter="formatfpointNo" align="left" label="所属楼" prop="fpointNo" />
      <el-table-column align="left" label="楼层编号" prop="flayerNo" />
      <el-table-column align="left" label="楼层名称" prop="flayerName" />
      <el-table-column :width="buttonColor.state" align="left" label="状态" prop="flayerState">
        <template slot-scope="scope">
          <span v-if="scope.row.flayerState==1" :style="{color:buttonColor.statestart}">{{ scope.row.flayerState | statusFilter }}</span>
          <span v-else :style="{color:buttonColor.statedisable}">{{ scope.row.flayerState | statusFilter }}</span>
        </template>
      </el-table-column>
    </JNPF-table>
    <paginations
      :total="total"
      :page.sync="listQuery.currentPage"
        :limit.sync="listQuery.pageSize"
        />
      </div>
    </div>
    <!-- 添加或修改对话框 -->
    <el-dialog :close-on-click-modal="false" top="10px" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="50%">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent label-width="95px" ref="dataForm" :rules="rules" :model="dataForm">
          <el-col :span="12">
            <el-form-item  label="楼层编号" prop="flayerNo">
              <el-input v-if="dialogStatus=='create'" v-model="dataForm.flayerNo"/>
              <el-input v-else v-model="dataForm.flayerNo" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item   label="客户名称" prop="fsiteNo">
              <el-select v-model="dataForm.fsiteNo" disabled clearable
              v-if="this.$store.state.user.fsiteLevel==3"
               filterable placeholder="请选择" @change="getStations(dataForm.fsiteNo,true)">
                <el-option
                  v-for="item in fsiteNoBelongOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
              <el-select v-else v-model="dataForm.fsiteNo" :disabled="dialogStatus=='update'" clearable filterable placeholder="请选择" @change="getStations(dataForm.fsiteNo,true)">
                <el-option
                  v-for="item in fsiteNoBelongOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="楼层名称" prop="flayerName">
              <el-input v-model="dataForm.flayerName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item  label="所属楼" prop="fpointNo">
              <el-select v-model="dataForm.fpointNo" clearable class="filter-item" placeholder="请选择所属楼">
                <el-option
                  v-for="item in eqtActionOptions"
                  :key="item.fpointNo"
                  :label="item.fpointName"
                  :value="item.fpointNo"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="fpointL">
              <el-input v-model="dataForm.fpointL"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经度" prop="fpointD">
              <el-input v-model="dataForm.fpointD"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="高度" prop="fpointH">
              <el-input v-model="dataForm.fpointH"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="宽度" prop="fpointW">
              <el-input v-model="dataForm.fpointW"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人">
              <el-input v-model="dataForm.fpersname">
                  <el-button slot="append" icon="el-icon-search" @click="searchDialoguse('add')"></el-button>
                </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="flayerState">
              <el-select v-model="dataForm.flayerState" clearable class="filter-item" placeholder="请选择状态">
                <el-option v-for="item in flayerStateList" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              class="text"
              style="width:100%"
              label="视频URL"
              prop="fvideoUrl">
              <el-input v-model="dataForm.fvideoUrl"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="平面图" prop="fimage">
              <el-upload
                v-model="dataForm.fimage"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :action="uploadPath"
                :data="formdata2(dataForm.fpointNo)"
                class="avatar-uploader">
                <img v-if="dataForm.fimage" :src="dataForm.fimage" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"/>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" v-if="dialogStatus=='create'"  @click="createData">确定</el-button>
        <el-button type="primary" v-else  @click="updateData">确定</el-button>
      </span>
    </el-dialog>
    <userDialog :search-visibleuse.sync="searchVisibleuse" :fsite-no.sync="userDialogFsiteNo" :table-color="tableColor" @userDialog="userDialogValue" />
  </div>
</template>

<script>
import { listtsLayer, createtsLayer, updatetsLayer, deletetsLayer } from '@/api/tsLayer'
import { uploadPath2 } from '@/api/room'
import { getToken } from '@/utils/auth'
import { fsiteOptionsByLevel } from '@/api/area'
import { listPointByFsiteNo2 } from '@/api/airAlarm'
import { tableColor, titleColor, buttonColor } from '@/filters/index'
import { uploadPath } from '@/api/eqtOrder'
import Pagination from '@/components/Pagination'
import moment from 'moment'
import UserDialog from '@/components/UserDialog'

const statusMap = {
  1: '启用',
  0: '禁用'
}

export default {
  name: 'ATsLayer',
  components: { Pagination, UserDialog },
  filters: {
    statusFilter(type) {
      return statusMap[type]
    }
  },
  data() {
    return {
      searchVisibleuse: false,
      userDialogFsiteNo: null,
      userFlag: null,
      tableColor,
      titleColor,
      buttonColor: buttonColor,
      statusMap,
      uploadPath2,
      uploadPath,
      fpointNoAll: [],
      eqtActionOptions: [],
      fpointOptions2: [],
      fsiteNoBelongOptions: [],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        flayerName: undefined,
        fsiteNo: undefined,
        fpointNo: undefined,
        fpointL: undefined,
        fpointD: undefined,
        fpointH: undefined,
        fpointW: undefined,
        fimage: undefined,
        fvideoUrl: undefined,
        fperson: undefined,
        fpersname:undefined,
        flayerState: undefined,
        fupddate: undefined,
        foperator: undefined,
        sort: 'create_time',
        order: 'desc'
      },
      dataForm: {
        flayerName: undefined,
        fsiteNo: undefined,
        fpointNo: undefined,
        fpointL: undefined,
        fpointD: undefined,
        fpointH: undefined,
        fpointW: undefined,
        fimage: undefined,
        fvideoUrl: undefined,
        fperson: undefined,
        flayerState: undefined,
        fupddate: undefined,
        foperator: undefined,
        id: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        flayerNo: [
          { required: true, message: '楼层编号不能为空' }
        ],
        flayerName: [
          { required: true, message: '楼层名称不能为空' }
        ],
        fsiteNo: [
          { required: true, message: '客户名称不能为空' }
        ],
        fpointNo: [
          { required: true, message: '所属楼不能为空' }
        ]
      },
      flayerStateList: [
        { value: 1, label: '启用' },
        { value: 0, label: '禁用' }
      ]
    }
  },
  computed: {
    headers() {
      return {
        'Authorization': getToken()
      }
    }
  },
  created() {
    if (this.$store.state.user.fsiteLevel == 3) {
      this.listQuery.fsiteNo = this.$store.state.user.fsiteNo
      listPointByFsiteNo2(this.$store.state.user.fsiteNo)
        .then(response => {
          this.fpointOptions2 = response.data.data.list
        })
        .catch(() => {
          this.fpointOptions2 = []
        })
    }
    this.getList()
    fsiteOptionsByLevel(3)
      .then(response => {
        this.fsiteNoBelongOptions = response.data.data.list
      })
      .catch(() => {
        this.fsiteNoBelongOptions = []
      })

      // 所属楼
    listPointByFsiteNo2()
      .then(response => {
        this.fpointNoAll = response.data.data.list
      })
      .catch(() => {
        this.fpointNoAll = []
      })
  },
  methods: {
    datetimeFormat(row, column) {
      const date = row[column.property]
      if (date === undefined || date === null) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    handleAvatarSuccess(res, file) {
      // this.dataForm.fimage = URL.createObjectURL(file.raw)
      this.dataForm.fimage = res.data
      const time = new Date().getTime()
      this.dataForm.fimage = `${this.dataForm.fimage}?time=${time}`
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isLt2M // isJPG &&
    },
    formdata2: function(fpointno) {
      // const formdata = new FormData()
      // formdata.append('fpointno', '123456')
      return { 'ftype': '1', 'fpointno': fpointno }
    },
    uploadFileSuccess: function(response) {
      this.$notify.success({
        title: '导入',
        message: response.data
      })
    },
    // 搜索人员弹出框
    searchDialoguse(value) {
      this.userFlag = value
      if (value === 'add') {
        this.userDialogFsiteNo = this.dataForm.fsiteNo
      } else {
        this.userDialogFsiteNo = this.listQuery.fsiteNo
      }
      this.searchVisibleuse = true
    },

    // 人员弹出框返回值
    userDialogValue(value) {
      this.dataForm.fpersname = value.user.username
      this.dataForm.fperson = value.user.id;
    },
    // 所属楼查找
    getFpointOptions(fsiteNo) {
      this.listQuery.fpointNo = undefined
      this.fpointOptions2 = []
      if (fsiteNo) {
        listPointByFsiteNo2(fsiteNo)
          .then(response => {
            this.fpointOptions2 = response.data.data.list
          })
          .catch(() => {
            this.fpointOptions2 = []
          })
      }
    },
    // 所属楼添加
    getStations(fsiteNo, flag) {
      this.eqtActionOptions = []
      if (flag) {
        this.dataForm.fpointNo = ''
        this.dataForm.fperson = ''
      }
      if (fsiteNo) {
        listPointByFsiteNo2(fsiteNo)
          .then(response => {
            this.eqtActionOptions = response.data.data.list
          })
          .catch(() => {
            this.eqtActionOptions = []
          })
      }
    },
    formatfpointNo(row) {
      if (this.fpointNoAll.length > 0) {
        for (let i = 0; i < this.fpointNoAll.length; i++) {
          if (row.fpointNo == this.fpointNoAll[i].fpointNo) {
            return this.fpointNoAll[i].fpointName
          }
        }
        return ''
      } else {
        return ''
      }
    },
    formatSite: function(row, column) {
      if (this.fsiteNoBelongOptions.length > 0) {
        for (let i = 0; i < this.fsiteNoBelongOptions.length; i++) {
          if (row.fsiteNo === this.fsiteNoBelongOptions[i].value) {
            return this.fsiteNoBelongOptions[i].label
          }
        }
        return ''
      } else {
        return ''
      }
    },
    getList() {
      this.listLoading = true
      listtsLayer(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        flayerName: undefined,
        fsiteNo: undefined,
        fpointNo: undefined,
        fpointL: undefined,
        fpointD: undefined,
        fpointH: undefined,
        fpointW: undefined,
        fimage: undefined,
        fvideoUrl: undefined,
        fperson: undefined,
        flayerState: undefined,
        fupddate: undefined,
        foperator: undefined,
        id: undefined
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.eqtActionOptions = []
      if (this.$store.state.user.fsiteLevel == 3) {
        this.dataForm.fsiteNo = this.$store.state.user.fsiteNo
        listPointByFsiteNo2(this.$store.state.user.fsiteNo)
          .then(response => {
            this.eqtActionOptions = response.data.data.list
          })
          .catch(() => {
            this.eqtActionOptions = []
          })
      }
      this.dataForm.flayerState = 1
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createtsLayer(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.data
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.getStations(row.fsiteNo, false)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updatetsLayer(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.flayerNo === this.dataForm.flayerNo) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.data
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('是否删除该资料', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletetsLayer(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.data
            })
          })
      })
    },
    indexMethod(index) {
      index = index + 1
      return index
    }
  }
}
</script>